package cz.spock.cms.template;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.springframework.stereotype.Service;

import cz.spock.cms.template.entity.TemplateSource;
import cz.spock.core.service.BaseService;
import freemarker.cache.TemplateLoader;

/**
 * implementation of TemplateLoader for free marker template engine
 * 
 * this class is responsible for accessing template sources in datastore
 * 
 * STATUS: final version, not tested
 * 
 * @author miso
 *
 */
@Service
public class DatastoreTemplateLoader extends BaseService implements TemplateLoader {
    
    @Override
    public void closeTemplateSource(Object template) throws IOException {
        if(template instanceof TemplateSource) {
            ((TemplateSource)template).getReader().close();
        }
    }

    /**
     * finds template with given name in datastore
     * 
     * returns null if template not found
     */
    public Object findTemplateSource(String name) throws IOException {
        if(name == null) {
            return null;
        }
        TemplateSource t = dao.ofy().query(TemplateSource.class).filter("name", name).get();
        return t;
    }

    @Override
    public long getLastModified(Object template) {
        if(!(template instanceof TemplateSource)) {
            return -1;
        }
        TemplateSource t = (TemplateSource) template;
        if(t.getLastModified() == null) {
            return -1;
        }
        return t.getLastModified().getTime();
    }

    @Override
    public Reader getReader(Object template, String encoding) throws IOException {
        if(!(template instanceof TemplateSource)) {
            return null;
        }
        TemplateSource t = (TemplateSource) template;
        t.setReader(new StringReader(t.getTemplate()));
        return t.getReader();
    }

}
